﻿using Abp.Application.Services;
using FwProject.AppHome.Dto;
using FwProject.BrandInfo.Dto;
using FwProject.ShopApplication;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Abp.Domain.Repositories;
using Abp.Runtime.Caching;
using Castle.Core.Logging;
using FwProject.ShoppingMall.Shop;
using FwProject.ShoppingMall.EventAdvertising;
using FwProject.ShoppingMall.Com;
using System.Linq;
using Abp.AutoMapper;
using FwProject.Shop.Dto;
using AutoMapper.QueryableExtensions;
using FwProject.Com.Dto;
using FwProject.EventAdvertising.Dto;
using X.PagedList;
using Abp.BackgroundJobs;
using FwProject.BackGround.AppShopPay;

namespace FwProject.BrandInfo
{
    /// <summary>
    /// 商城首页数获取
    /// </summary>
    public class HomeShopAppService : FwProjectAppServiceBase, IHomeShopAppService
    {
        private readonly ICacheManager _catchmanager;
        private readonly IRepository<ShopType, Guid> _repositoryShopType;//商品分类
        private readonly IRepository<ShopProduct, Guid> _repositoryShopProduct;//具体商品
        private readonly IRepository<ShopSecondkill, Guid> _repositoryShopSecondkill;//秒杀商品
        private readonly IRepository<ShopAd, Guid> _repositoryShopAd;//广告列表
        private readonly IRepository<ShopOrder, Guid> _repositoryShopOrder;//订单
        private readonly IRepository<ShopOrderDetails, Guid> _repositoryShopOrderDetails;//广告列表
        private readonly IShopSecondkillAppService _shopSecondkillAppService;

        private readonly IBackgroundJobManager _backgroundJobManager;

        /// <summary>
        /// 日志记录
        /// </summary>
        public ILogger logging { get; set; }
        /// <summary>
        /// 数据映射
        /// </summary>
        public IObjectMapper _map { get; set; }
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="catchmanager"></param>
        /// <param name="repositoryShopType"></param>
        /// <param name="repositoryShopProduct"></param>
        /// <param name="repositoryShopSecondkill"></param>
        /// <param name="repositoryShopAd"></param>
        /// <param name="repositoryShopOrder"></param>
        /// <param name="repositoryShopOrderDetails"></param>
        public HomeShopAppService(ICacheManager catchmanager, IRepository<ShopType, Guid> repositoryShopType
            , IRepository<ShopProduct, Guid> repositoryShopProduct
             ,IRepository<ShopSecondkill, Guid> repositoryShopSecondkill, IRepository<ShopAd, Guid> repositoryShopAd
            , IRepository<ShopOrder, Guid> repositoryShopOrder, IRepository<ShopOrderDetails, Guid> repositoryShopOrderDetails,
             IShopSecondkillAppService shopSecondkillAppService,
             IBackgroundJobManager backgroundJobManager
            ) {
            _backgroundJobManager = backgroundJobManager;
            _shopSecondkillAppService = shopSecondkillAppService;
            logging = NullLogger.Instance;
            _catchmanager = catchmanager;
            _repositoryShopType = repositoryShopType;
            _repositoryShopProduct = repositoryShopProduct;
            _repositoryShopSecondkill = repositoryShopSecondkill;
            _repositoryShopAd = repositoryShopAd;
            _repositoryShopOrder = repositoryShopOrder;
            _repositoryShopOrderDetails = repositoryShopOrderDetails;

        }



        /// <summary>
        /// 获取首页数据
        /// </summary>
        /// <returns>得到所有的分类HomeShopType 首页banner BannerAd 首页宣传广告 PropagandaAd 推荐RecommendProduct 特价SaleProduct</returns>
        public HomeDto GetHomeShop() {

            return GetCatch;
        }
        /// <summary>
        /// 根据缓存获取
        /// </summary>
        private HomeDto GetCatch {

            get {
                ICache cache = _catchmanager.GetCache(nameof(HomeDto));
                return  cache.Get("index",() =>  GetData());
            }

        }
        private HomeDto GetData() {
            HomeDto homeDto = new HomeDto();
            //得到所有的分类
            var ShopTypeDto = _repositoryShopType.GetAll().Where(o => o.Isactive == true && o.Parentid==null).ProjectTo<ShopTypeDto>();
            homeDto.HomeShopType = ShopTypeDto.MapTo<List<HomeShopType>>();
            //首页banner
            var ShopAdDto = _repositoryShopAd.GetAllIncluding(o => o.ShopAdLocation).Where(o => o.AdbeginTime <= DateTime.Now && o.AdEndTime >= DateTime.Now && o.IsActive==true && o.ShopAdLocation.AdTypeLocation == AdTypeLocation.首页banner).ProjectTo<ShopAdDto>();
            homeDto.BannerAd = ShopAdDto.MapTo<List<HomeBanner>>();
            //首页宣传广告
            var ShopPropagandaAdDto = _repositoryShopAd.GetAll().Where(o => o.AdbeginTime <= DateTime.Now && o.AdEndTime >= DateTime.Now && o.IsActive == true && o.ShopAdLocation.AdTypeLocation == AdTypeLocation.首页横幅广告).ProjectTo<ShopAdDto>();
            homeDto.PropagandaAd = ShopPropagandaAdDto.MapTo<List<HomeBanner>>();

            var ShopProductDtolist = _repositoryShopProduct.GetAll().Where(o => o.IsGrounding == true);
            var order = _repositoryShopOrderDetails.GetAll().Where(o => o.DeliveryTime != null);
            //推荐
            homeDto.RecommendProduct = ShopProductDtolist.Where(o => o.ShopProductFlag == ShopProductFlag.推荐).GroupJoin(order.GroupBy(o => o.ShopproductId).Select(o => new { id = o.Key, ProductCount = o.Sum(t => t.ProductCount) }),
                k => k.Id, m => m.id, (t, n) => new HomeShopProduct
                {
                    Id = t.Id,
                    ShopTypeid = t.ShopTypeid,
                    ProductName = t.ProductName,
                    ProductNumber = t.ProductNumber,
                    ShopProductFlag = t.ShopProductFlag,
                    Unit = t.Unit,
                    SpceWeight = t.SpceWeight,
                    SpcemarketPrice = t.SpcemarketPrice,
                    MarketPrice=t.MarketPrice,
                    PayPeopleCount = order.Where(o => o.ShopproductId == t.Id).Count(),
                    PayCount = n.Sum(o => o.ProductCount),
                    HomeImage = t.ImagePic

                }).ToList();
            //特价
            homeDto.SaleProduct = ShopProductDtolist.Where(o => o.ShopProductFlag == ShopProductFlag.特价).GroupJoin(order.GroupBy(o => o.ShopproductId).Select(o => new { id = o.Key, ProductCount = o.Sum(t => t.ProductCount) }),
                k => k.Id, m => m.id, (t, n) => new HomeShopProduct
                {
                    Id = t.Id,
                    ShopTypeid = t.ShopTypeid,
                    ProductName = t.ProductName,
                    ProductNumber = t.ProductNumber,
                    ShopProductFlag = t.ShopProductFlag,
                    Unit = t.Unit,
                    SpceWeight = t.SpceWeight,
                    SpcemarketPrice = t.SpcemarketPrice,
                    MarketPrice = t.MarketPrice,
                    PayPeopleCount = order.Where(o => o.ShopproductId == t.Id).Count(),
                    PayCount = n.Sum(o => o.ProductCount),
                    HomeImage = t.ImagePic
                }).ToList();

            var killone = _repositoryShopAd.GetAllIncluding(o => o.ShopAdLocation).Where(o => o.AdbeginTime <= DateTime.Now && o.AdEndTime >= DateTime.Now && o.IsActive == true && o.ShopAdLocation.AdTypeLocation == AdTypeLocation.秒杀长图).ProjectTo<ShopAdDto>().FirstOrDefault();
            homeDto.SecKillProduct = new List<HomeBanner>();
            if(killone!=null)
                homeDto.SecKillProduct.Add(killone.MapTo<HomeBanner>());

            var killlist = _repositoryShopAd.GetAllIncluding(o => o.ShopAdLocation).Where(o => o.AdbeginTime <= DateTime.Now && o.AdEndTime >= DateTime.Now && o.IsActive == true && o.ShopAdLocation.AdTypeLocation == AdTypeLocation.首页秒杀).Skip(0).Take(7).ProjectTo<ShopAdDto>();

            if (killlist!=null)
            homeDto.SecKillProduct.AddRange(killlist.MapTo<List<HomeBanner>>());

            return homeDto;
        }

        /// <summary>
        /// 获取产品分类
        /// </summary>
        /// <returns></returns>
        public List<HomeShopType> GetHomeShopType() {

            var ShopTypeDto = _repositoryShopType.GetAll().Where(o => o.Isactive == true).ProjectTo<ShopTypeDto>();
            return ShopTypeDto.MapTo<List<HomeShopType>>();
        }
        /// <summary>
        /// 获取首页banner广告
        /// </summary>
        /// <returns></returns>
        public List<HomeBanner> GetHomeBanner()
        {

            var ShopAdDto = _repositoryShopAd.GetAllIncluding(o => o.ShopAdLocation).Where(o => o.AdEndTime >= DateTime.Now && o.ShopAdLocation.AdTypeLocation == AdTypeLocation.首页banner).ProjectTo<ShopAdDto>();
            return ShopAdDto.MapTo<List<HomeBanner>>();
        }
        /// <summary>
        /// 获取首页横浮广告
        /// </summary>
        /// <returns></returns>
        public List<HomeBanner> GetShopPropagandaAdDto()
        {

             var ShopPropagandaAdDto = _repositoryShopAd.GetAll().Where(o => o.AdEndTime >= DateTime.Now && o.ShopAdLocation.AdTypeLocation == AdTypeLocation.首页横幅广告).ProjectTo<ShopAdDto>();
             return ShopPropagandaAdDto.MapTo<List<HomeBanner>>();
        }
        /// <summary>
        /// 推荐商品
        /// </summary>
        /// <returns></returns>
        public List<HomeShopProduct> GetRecommendShopProductDtolist()
        {

            var ShopProductDtolist = _repositoryShopProduct.GetAll().Where(o => o.IsGrounding == true);
            var order = _repositoryShopOrderDetails.GetAll().Where(o => o.DeliveryTime != null);
            //推荐
            return ShopProductDtolist.Where(o => o.ShopProductFlag == ShopProductFlag.推荐).GroupJoin(order.GroupBy(o => o.ShopproductId).Select(o => new { id = o.Key, ProductCount = o.Sum(t => t.ProductCount) }),
                k => k.Id, m => m.id, (t, n) => new HomeShopProduct
                {
                    Id = t.Id,
                    ShopTypeid = t.ShopTypeid,
                    ProductName = t.ProductName,
                    ProductNumber = t.ProductNumber,
                    ShopProductFlag = t.ShopProductFlag,
                    Unit = t.Unit,
                    SpceWeight = t.SpceWeight,
                    SpcemarketPrice = t.SpcemarketPrice,
                    MarketPrice = t.MarketPrice,
                    PayPeopleCount = order.Where(o => o.ShopproductId == t.Id).Count(),
                    PayCount = n.Sum(o => o.ProductCount),
                    HomeImage = t.ImagePic

                }).ToList();
        }

        /// <summary>
        /// 特价商品
        /// </summary>
        /// <returns></returns>
        public IPagedList<HomeShopProduct> GetSaleProduct(int page,int pageSize)
        {

            var ShopProductDtolist = _repositoryShopProduct.GetAll().Where(o => o.IsGrounding == true);
            var order = _repositoryShopOrderDetails.GetAll().Where(o => o.DeliveryTime != null);
            //推荐
            return ShopProductDtolist.Where(o => o.ShopProductFlag == ShopProductFlag.特价).GroupJoin(order.GroupBy(o => o.ShopproductId).Select(o => new { id = o.Key, ProductCount = o.Sum(t => t.ProductCount) }),
                k => k.Id, m => m.id, (t, n) => new HomeShopProduct
                {
                    Id = t.Id,
                    ShopTypeid = t.ShopTypeid,
                    ProductName = t.ProductName,
                    ProductNumber = t.ProductNumber,
                    ShopProductFlag = t.ShopProductFlag,
                    Unit = t.Unit,
                    SpceWeight = t.SpceWeight,
                    SpcemarketPrice = t.SpcemarketPrice,
                    MarketPrice = t.MarketPrice,
                    PayPeopleCount = order.Where(o => o.ShopproductId == t.Id).Count(),
                    PayCount = n.Sum(o => o.ProductCount),
                    HomeImage = t.ImagePic

                }).ToPagedList(page,pageSize);
        }

        /// <summary>
        /// 秒杀商品
        /// </summary>
        /// <returns></returns>
        public List<HomeSecKillShopProduct> GetHomeSecKillShopProduct()
        {
            var ShopProductDtolist = _repositoryShopProduct.GetAll().Where(o => o.IsGrounding == true);
            var order = _repositoryShopOrderDetails.GetAll().Where(o => o.DeliveryTime != null);
            //推荐
            var killlist = _repositoryShopSecondkill.GetAll().Where(o => o.SecondkillEndTime <= DateTime.Now);
            return killlist.Join(ShopProductDtolist, o => o.ShopProductId, t => t.Id, (t, n) => new HomeSecKillShopProduct
            {
                Id = t.Id,
                ShopTypeid = n.ShopTypeid,
                ShopProductid = n.Id,
                ProductName = n.ProductName,
                ProductNumber = n.ProductNumber,
                ShopProductFlag = n.ShopProductFlag,
                Unit = n.Unit,
                SpceWeight = n.SpceWeight,
                PayPeopleCount = order.Where(o => o.ShopproductId == t.Id && o.CreationTime >= t.SecondkillBeginTime).Count(),
                PayCount = order.Where(o => o.ShopproductId == t.Id && o.CreationTime >= t.SecondkillBeginTime).Sum(o => o.ProductCount),
                HomeImage = n.ImagePic,

            }).ToList();
        }
    }
}
